package cn.smdq.ch.gateway.core.route;

import cn.smdq.ch.common.constant.CommonConstants;
import cn.smdq.ch.common.dto.RoutesDTO;
import com.google.common.collect.Sets;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;


/**
 * @author shuimodanqing
 * create at:  2019/1/24  1:29 PM
 * @description redis中加载路由
 */
public class RedisZuulRouteLocator extends ZuulRouteLocator {

    private RedisTemplate redisTemplate;

    public RedisZuulRouteLocator(String servletPath, ZuulProperties properties, RedisTemplate redisTemplate) {
        super(servletPath, properties);
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected Map<String, ZuulProperties.ZuulRoute> loadLocateRoute() {

        Map<String, ZuulProperties.ZuulRoute> routeMapToUse = new LinkedHashMap<>();
        //从redis中加载路由信息
        Object objForRoute = redisTemplate.opsForValue().get(CommonConstants.GATEWAY_ROUTE_KEY);
        if (objForRoute == null) {
            return routeMapToUse;
        }
        if (objForRoute instanceof List) {
            List<RoutesDTO> routesDTOList = (List<RoutesDTO>) objForRoute;
            Consumer<RoutesDTO> routeHandler = routeDto -> {
                ZuulProperties.ZuulRoute zuulRoute = new ZuulProperties.ZuulRoute();
                zuulRoute.setId(routeDto.getServiceId());
                zuulRoute.setPath(routeDto.getPath());
                zuulRoute.setRetryable(routeDto.getRetryable());
                zuulRoute.setStripPrefix(routeDto.getStripPrefix());
                zuulRoute.setCustomSensitiveHeaders(true);
                zuulRoute.setUrl(routeDto.getUrl());
                zuulRoute.setServiceId(routeDto.getServiceId());
                String[] sensitiveHeaders = routeDto.getSensitiveHeaderSet().split(",");
                if (sensitiveHeaders.length > 0) {
                    zuulRoute.setSensitiveHeaders(Sets.newHashSet(routeDto.getSensitiveHeaderSet().split(",")));
                }
                routeMapToUse.put(zuulRoute.getPath(), zuulRoute);
            };
            if (routesDTOList.size() > 0) {
                routesDTOList.forEach(routeHandler);
            }
        }
        return routeMapToUse;
    }

}
